<script setup>
import { ref, onMounted, watch, computed, nextTick } from 'vue'
//导入markdown相关插件
import MarkdownIt from 'markdown-it'
import 'github-markdown-css'

// 引入ai store
import { useAIStore } from '@/stores/modules/ai.js'
const aiStore = useAIStore()
const boxContainer = ref(null)

const md = new MarkdownIt()
// 计算属性来实时转换Markdown内容
const renderedTalkList = computed(() => {
  return talkList.value.map((item) => ({
    ...item,
    content: item.status === 0 ? md.render(item.content) : item.content,
  }))
})

let talkList = ref([])

const loadTalkListData = () => {
  talkList.value = aiStore.talkList
}

// 滚动到底部的方法
const scrollToBottom = () => {
  nextTick(() => {
    if (boxContainer.value) {
      boxContainer.value.scrollTop = boxContainer.value.scrollHeight
    }
  })
}

// 监听事件
const props = defineProps({
  refreshChatBoxFlag: {
    type: Boolean,
    default: false,
  },
})

watch(
  () => talkList.value,
  () => {
    scrollToBottom()
  },
  { deep: true },
)

// 监听refreshChatBoxFlag的变化
watch(
  () => props.refreshChatBoxFlag,
  () => {
    loadTalkListData()
  },
)

onMounted(() => {
  loadTalkListData()
  scrollToBottom()
})
</script>

<template>
  <div class="box-container" ref="boxContainer">
    <div class="talks" v-for="item in renderedTalkList">
      <!--  这是AI的回答  -->
      <div v-if="item.status === 0" class="talk-bar1">
        <div class="markdown-body" v-html="item.content"></div>
      </div>

      <!--  这是用户的问题  -->
      <div v-if="item.status === 1" class="talk-bar2">{{ item.content }}</div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.box-container {
  width: 68%;
  height: 100%;
  overflow: auto;
  -ms-overflow-style: none;
  scrollbar-width: none;
  .talks {
    margin-top: 25px;
    .talk-bar1 {
      float: left;
      clear: both;
      max-width: 1080px;
      padding: 16px 20px;
      background: rgba(255, 255, 255, 1);
      color: rgba(51, 51, 51, 1);
      letter-spacing: 1px;
      border-radius: 0 30px 30px 30px;
      margin-left: 40px;
      box-shadow: 0 5px 15px rgba(201, 201, 201, 0.2);
      font-size: 16px;
      line-height: 30px;
      margin-bottom: 20px;
    }
    .talk-bar2 {
      width: fit-content;
      max-width: 800px;
      float: right;
      clear: both;
      padding: 16px 20px;
      background: linear-gradient(
        270deg,
        rgba(198, 173, 255, 0.2) 0%,
        rgba(102, 170, 237, 0.2) 100%
      );
      letter-spacing: 1px;
      border-radius: 30px 0 30px 30px;
      margin-right: 40px;
      font-size: 16px;
      line-height: 30px;
      margin-bottom: 20px;
    }
  }
}
</style>
